package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发送语音
     * @param sound
     */
    @Override
    public void saveSound(Sound sound) {
        sound.setSid(idWorker.getNextId("sound"));
        mongoTemplate.insert(sound);
    }

    /**
     * 随机查询语音
     * @param userId
     * @return
     */
    @Override
    public Sound getSoundByRecommend(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        //查询好友表，排除好友的id
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        List<Long> idsList = new ArrayList<>();
        if (!CollUtil.isEmpty(friendList)) {
            List<Long> friendIds = CollUtil.getFieldValues(friendList, "friendId", Long.class);
            idsList.addAll(friendIds);
        }
        //查询喜欢表，排除喜欢的id
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        if (!CollUtil.isEmpty(userLikeList)) {
            List<Long> likeUserIds = CollUtil.getFieldValues(userLikeList, "likeUserId", Long.class);
            idsList.addAll(likeUserIds);
        }
        //排除自己
        idsList.add(userId);
        //构造条件
        Query soundQuery = Query.query(Criteria.where("userId").nin(idsList).and("state").is("0"));
        //soundQuery.addCriteria(Criteria.where("userId").nin(idsList));
        //根据 soundQuery 获取 soundList
        List<Sound> soundList = mongoTemplate.find(soundQuery, Sound.class);
        if (CollUtil.isEmpty(soundList)) {
            return null;
        }
        //随机取集合的中的 sound 返回
        return soundList.get(RandomUtil.randomInt(0, soundList.size()));
    }

    /**
     * 根据sid修改
     * @param sound
     */
    @Override
    public void updateById(Sound sound) {
        Query query = Query.query(Criteria.where("sid").is(sound.getSid()));
        Update update = new Update();
        update.set("state", sound.getState());
        mongoTemplate.updateFirst(query, update, Sound.class);
    }
}
